package com.example.sl;

import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.sl.Utils.ToastUtil;
import com.example.sl.database.UserHelper;
import com.example.sl.model.UserInfo;

import java.util.List;

public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {

    UserHelper userHelper;
    EditText name;
    EditText age;
    Spinner sex;
    EditText addr;
    TextView msg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        name = findViewById(R.id.name);
        age = findViewById(R.id.age);
        sex = findViewById(R.id.sex);
        addr = findViewById(R.id.addr);
        msg = findViewById(R.id.msg);

        Button add = findViewById(R.id.add);
        Button delete = findViewById(R.id.delete);
        Button update = findViewById(R.id.update);
        Button query = findViewById(R.id.query);
        Button trans = findViewById(R.id.trans);


        add.setOnClickListener(this);
        delete.setOnClickListener(this);
        update.setOnClickListener(this);
        query.setOnClickListener(this);
        trans.setOnClickListener(this);

        userHelper = new UserHelper(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id==R.id.add){
            UserInfo userInfo = new UserInfo();
            userInfo.setName(name.getText().toString());
            userInfo.setAge(Integer.parseInt(age.getText().toString()));
            userInfo.setSex(sex.getSelectedItem().toString());
            userInfo.setAddr(addr.getText().toString());
            long l = userHelper.insertUser(userInfo);
            ToastUtil.show(MainActivity2.this,"添加了一条记录:"+l);
        }else if(id == R.id.delete){
            int result = userHelper.deleteUser("yejing");
            ToastUtil.show(MainActivity2.this,"删除了一条记录:"+result);
        }else if(id == R.id.update){
            UserInfo userInfo = new UserInfo();
            userInfo.setName(name.getText().toString());
            userInfo.setAge(Integer.parseInt(age.getText().toString()));
            userInfo.setSex(sex.getSelectedItem().toString());
            userInfo.setAddr(addr.getText().toString());
            int result = userHelper.updateUser(userInfo);
            ToastUtil.show(MainActivity2.this,"修改了一条记录:"+result);
        }else if(id == R.id.query){
            List<UserInfo> userInfos = userHelper.queryUser();
            msg.setText(userInfos.toString());
        }else if(id == R.id.trans){
            userHelper.insertTwoUser();
        }

    }
}